

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[][]}
 */
function threeSum(nums, target) {
    let res = [];
    let n = nums.length;
    if (nums == null || n < 3) return res;
    nums.sort((a, b) => a - b);

    for (let i = 0; i < n - 2; i++) {
        if (nums[i] === nums[i - 1]) continue;
        let left = i + 1;
        let right = n - 1;
        while (left < right) {
            let sum = nums[i] + nums[left] + nums[right];
            if (sum === target) {
                res.push([nums[i], nums[left++], nums[right--]]);
                while (nums[left] === nums[left - 1]) left++;
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
    }
    return res;
}
console.log(threeSum([2, 11, 20, 160, 3, 1, 77], 100));